package com.yisu.expressway.login;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.model.LoginEvent;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.utils.SMSUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

public class VerificationCodeLoginActivity extends BaseActivity implements TextWatcher{

    @Bind(R.id.verify_mobile_number)
    protected TextView mTextViewPhoneNumber;
    @Bind(R.id.verify_verification_code)
    protected EditText mEditTextVerificationCode;
    @Bind(R.id.verify_send)
    protected Button mButtonResend;
    @Bind(R.id.verify_btn_ok)
    protected Button mButtonOk;

    public static final String INTENT_KEY_PHONE_NUMBER = "phone_number";

    private String mPhoneNumber;
    private CountDownTask task;
    private int count;
    private static final int MSG_REFRESH_TIME = 101;

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REFRESH_TIME:
                    int timeCount = (Integer) msg.obj;

                    if(mButtonResend == null){
                        return;
                    }

                    if (timeCount > 0) {
                        mButtonResend.setText(count + "");
                        mButtonResend.setClickable(false);
                    }else {
                        mButtonResend.setText(getResources().getString(R.string.login_resend_veification_code));
                        mButtonResend.setClickable(true);
                        task.cancel();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification_code_login);
        setTitle("输入验证码");
        final MultiButtonDialog dialog = new MultiButtonDialog(this);
        mTitleBar.setClickBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
                dialog.setContentText("验证码短信可能略有延迟，确定返回并重新开始？");
                dialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
                    @Override
                    public void onPositiveClick(String inputContent) {
                        dialog.dismiss();
                        finish();
                    }
                });
            }
        });

        initView();
        showWaitTime();

        mEditTextVerificationCode.setFocusable(true);
        mEditTextVerificationCode.setFocusableInTouchMode(true);
        mEditTextVerificationCode.requestFocus();
        mEditTextVerificationCode.requestFocusFromTouch();
        mEditTextVerificationCode.addTextChangedListener(this);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(getCurrentFocus(), InputMethodManager.SHOW_FORCED);
    }

    private void initView() {
        mButtonOk.setEnabled(false);
        mPhoneNumber = getIntent().getStringExtra(INTENT_KEY_PHONE_NUMBER);
        mTextViewPhoneNumber.setText(mPhoneNumber);
    }

    @OnClick( {R.id.verify_btn_ok,R.id.verify_send})
    public void doOnClick(Button button){
        switch (button.getId()) {
            case R.id.verify_btn_ok:
                String mobile = mTextViewPhoneNumber.getText().toString();
                String code = mEditTextVerificationCode.getText().toString();
                if (code.length() == 0) {
                    ToastUtil.displayShortToastMsg(VerificationCodeLoginActivity.this, "输入验证码");
                }
                doLoginAction(mobile, code);
                break;
            case R.id.verify_send:
                SMSUtil.sendSmsRequest(null, mPhoneNumber);
                showWaitTime();
                break;
        }
    }

    public void showWaitTime() {
        count = 60;
        Timer timer = new Timer();
        task = new CountDownTask();
        timer.schedule(task, new Date(), 1000);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = mEditTextVerificationCode.getText().toString();
        if (text.length() == 4) {
            mButtonOk.setEnabled(true);
        }else{
            mButtonOk.setEnabled(false);
        }
    }

    public class CountDownTask extends TimerTask {
        public void run(){
            Message message = new Message();
            message.what = MSG_REFRESH_TIME;
            message.obj = count;
            handler.sendMessage(message);
            count --;
        }
    }

    private void doLoginAction(String mobile, String verifyCode){

        Map<String, Object> params = new HashMap();
        params.put("userAccount", mobile);
        params.put("accountType",0);
        params.put("validateCode",verifyCode);
        params.put("deviceType",2);
        if(!StringUtil.isNullOrEmpty(LoginManager.getPushClientId())){
            params.put("pushType",1);
            params.put("pushClientId",LoginManager.getPushClientId());
        }

        ApiClientHelper.postApi(ApiSetting.loginIn(), new TypeToken<UserProfile>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<UserProfile>>() {
            @Override
            public void onResponse(ApiResult<UserProfile> result) {
                if (!result.success) {
                    EventBus.getDefault().post(new LoginEvent(false));
                    ToastUtil.displayLongToastMsg(VerificationCodeLoginActivity.this, result.getMsg());
                    return;
                }

                UserProfile userProfile = result.getResult();
                if(userProfile != null){
                    LoginManager.onLoginSuccess(userProfile);
                    ToastUtil.showMessage(VerificationCodeLoginActivity.this, "登录成功");
                    EventBus.getDefault().post(new LoginEvent(true));
                    finish();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                EventBus.getDefault().post(new LoginEvent(false));
                ToastUtil.displayShortToastMsg(VerificationCodeLoginActivity.this, volleyError.getMessage());
            }
        }, this);
    }


}
